package com.zang.test.rocketmq.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Zhang Qiang
 * @date 2019/10/31 9:51
 */
@Slf4j
@Component
public class Producer {

    @Value("${apache.rocketmq.producer.producerGroup}")
    private String producerGroup;

    @Value("${apache.rocketmq.namesrvAddr}")
    private String namervAddr;

    @PostConstruct
    public void defaultMQProducer(){
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(producerGroup);
        defaultMQProducer.setNamesrvAddr(namervAddr);
        try {
            defaultMQProducer.start();
            String message = "send message by mq to ";
            for (int i = 0; i < 10; i++) {
                String sendMsg = new String((message + i).getBytes(), "UTF-8" );
                Message msg = new Message("PushTopic", "push", "key_" + i, sendMsg.getBytes());
                SendResult result = defaultMQProducer.send(msg);
                log.info("发送消息 ： {}", msg);
            }
        } catch (Exception e) {
            log.info(" message：{} ", e.getMessage() );
        }


    }



}
